package com.august.shop.product.service.impl;

import com.august.shop.product.service.CategoryBrandRelationService;
import com.august.shop.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.august.common.utils.PageUtils;
import com.august.common.utils.Query;

import com.august.shop.product.dao.CategoryDao;
import com.august.shop.product.entity.CategoryEntity;
import com.august.shop.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构
        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //@Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLeve1Categorys() {
        System.out.println("CategoryServiceImpl.getLeve1Categorys (获取一级分类)调用了");
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntityList;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
        return catalogJsonFromDb;
    }


    // @Cacheable(value = {"category"}, key = "#root.methodName", sync = true)
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        System.out.println("查询了数据库。。。。");
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        // 1、查询所有一级分类
        List<CategoryEntity> leve1Categorys = getParentCid(categoryEntityList, 0L);

        // 2、封装需要的数据
        Map<String, List<Catelog2Vo>> map = leve1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            // 根据每个一级分类，查询到他的二级分类
            List<CategoryEntity> category2EntityList = getParentCid(categoryEntityList, v.getCatId());

            // 抽取出前台需要的的二级分类vo
            List<Catelog2Vo> l2VoList = null;

            if (category2EntityList != null) {

                l2VoList = category2EntityList.stream().map(l2 -> {
                    // 当前一级分类的2级分类vo
                    Catelog2Vo l2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    // 封装当前二级分类vo的三级分类vo
                    List<CategoryEntity> l3EntityList = getParentCid(categoryEntityList, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> l3VoList = null;
                    if (l3EntityList != null) {
                        l3VoList = l3EntityList.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo l3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return l3Vo;
                        }).collect(Collectors.toList());
                    }
                    // 给二级分类vo设置封装好的三级分类vo
                    l2Vo.setCatalog3List(l3VoList);
                    return l2Vo;
                }).collect(Collectors.toList());
            }
            return l2VoList;
        }));

        return map;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoryEntityList, Long parentCid) {

        List<CategoryEntity> collect = categoryEntityList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}